﻿@page "/export-chart"

@using PdfExportJS.Services
@inject DrawingService DrawingService

<TelerikButton Icon="image" OnClick="@ExportChartToJPG">Export to .jpg</TelerikButton>

<div @ref="ExportChart">
    <TelerikChart Height="480px" Width="640px">

        <ChartSeriesItems>
            <ChartSeries Type="@ChartSeriesType.OHLC"
                         Name="Product 1"
                         Data="@ChartProduct1Data"
                         CategoryField="@(nameof(StockDataPoint.Date))"
                         OpenField="@nameof(StockDataPoint.Open)"
                         CloseField="@nameof(StockDataPoint.Close)"
                         HighField="@nameof(StockDataPoint.High)"
                         LowField="@nameof(StockDataPoint.Low)">
            </ChartSeries>
        </ChartSeriesItems>

        <ChartCategoryAxes>
            <ChartCategoryAxis Type="@ChartCategoryAxisType.Date" BaseUnit="@ChartCategoryAxisBaseUnit.Months">
            </ChartCategoryAxis>
        </ChartCategoryAxes>

        <ChartValueAxes>
            <ChartValueAxis>
                <ChartValueAxisLabels Format="{0:C4}"></ChartValueAxisLabels>
            </ChartValueAxis>
        </ChartValueAxes>

    </TelerikChart>
</div>


@code {
    ElementReference ExportChart { get; set; }

    //Export the Chart to jpg
    async Task ExportChartToJPG()
    {
        var data = await DrawingService.ExportImage(ExportChart);
        await DrawingService.SaveAs(data, "MyExportedChartJPG.jpg");
    }

    List<StockDataPoint> ChartProduct1Data { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await GenerateChartData();
    }

    async Task GenerateChartData()
    {
        ChartProduct1Data = new List<StockDataPoint>()
{
            new StockDataPoint(new DateTime(2019, 1, 1), 39.88m, 40.12m, 41.12m, 39.75m, 3584700),
            new StockDataPoint(new DateTime(2019, 2, 1), 41.62m, 40.12m, 41.69m, 39.81m, 2632000),
            new StockDataPoint(new DateTime(2019, 3, 1), 42m, 42.62m, 43.31m, 41.38m, 7631700),
            new StockDataPoint(new DateTime(2019, 4, 1), 42.25m, 43.06m, 43.31m, 41.12m, 4922200),
        };

        await Task.FromResult(ChartProduct1Data);
    }

    public class StockDataPoint
    {
        public StockDataPoint() { }

        public StockDataPoint(DateTime date, decimal open, decimal close, decimal high, decimal low, int volume)
        {
            Date = date;
            Open = open;
            Close = close;
            High = high;
            Low = low;
            Volume = volume;
        }
        public DateTime Date { get; set; }

        public decimal Open { get; set; }

        public decimal Close { get; set; }

        public decimal High { get; set; }

        public decimal Low { get; set; }

        public int Volume { get; set; }
    }
}